package com.jvm.interpreter.instruction;

import com.jvm.classfile.model.CpInfo;
import com.jvm.interpreter.Frame;
import com.jvm.interpreter.Instruction;

/**
 * @program: diy_simple_jvm
 * @description: if_icmpgt指令
 * @author: CaoYong
 * @create: 2021-07-08 13:36
 **/
public class IfIcmpGtInst implements Instruction {

    public  final int offset;

    public IfIcmpGtInst(int offset) {
        this.offset = offset;
    }

    /**
     * 比较栈顶两个数的大小，将栈顶两个数出栈，如果后出栈的数字大于先出栈的数字，则将程序计数器设置为指令参数对应的值，否则进行下一指令
     * @param frame 栈帧
     */
    @Override
    public void eval(Frame frame) {
//        int v2 = frame.operandStack.pop();
//        int v1 = frame.operandStack.pop();
        int v2 = frame.popInt();
        int v1 = frame.popInt();

        if (v1 > v2) {
            frame.pc += offset;
        } else {
            frame.pc += offset();
        }
    }

    @Override
    public int offset() {
        return 3;
    }

    static IfIcmpGtInst parse(java.io.DataInputStream dis, CpInfo[] cp) throws java.io.IOException {
        return new IfIcmpGtInst(dis.readShort());
    }
}
